<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.all()</title>
</head>
<body>
    <h1>Promise.all()</h1>
    <h2>将多个Promise实例，包装成一个新的Promise实例</h2>

    <script>
        // 基本用法
        const p1 = Promise.resolve(3);
        const p2 = new Promise(resolve => setTimeout(() => resolve(2), 100));
        const p3 = new Promise(resolve => setTimeout(() => resolve(1), 200));

        Promise.all([p1, p2, p3])
            .then(values => {
                console.log(values); // [3, 2, 1]
            });

        // 有一个被reject
        const p4 = Promise.resolve(1);
        const p5 = Promise.reject('出错了');
        const p6 = Promise.resolve(3);

        Promise.all([p4, p5, p6])
            .then(values => {
                console.log('不会执行');
            })
            .catch(error => {
                console.log(error); // "出错了"
            });

        // 实际应用：多个请求并发执行
        function mockFetch(url) {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve(`来自 ${url} 的数据`);
                }, Math.random() * 1000);
            });
        }

        Promise.all([
            mockFetch('/api/users'),
            mockFetch('/api/posts'),
            mockFetch('/api/comments')
        ]).then(results => {
            console.log('所有请求完成:', results);
        });
    </script>
</body>
</html> 